package com.lyx.question.mq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lyx.common.constant.RedisContant;
import com.lyx.common.result.R;
import com.lyx.question.dto.PaperWitnQuestionDto;
import com.lyx.question.dto.UserDto;
import com.lyx.question.entity.Paper;
import com.lyx.question.feign.UserFeignService;
import com.lyx.question.service.PaperService;
import com.lyx.question.service.QuestionSmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Objects;

/**
 * @author 14667
 * @date 2022/8/1 15:23
 */
@Slf4j
@Component
@RocketMQMessageListener(consumerGroup = "GID-ROCKET_SBD-GROUP-1",topic = "sbd-topic-test")
public class Consumer implements RocketMQListener<MessageExt> {
    @Autowired
    StringRedisTemplate redisTemplate;

    @Qualifier("questionSmsServiceImpl")
    @Autowired
    QuestionSmsService smsService;

    @Autowired
    UserFeignService userFeignService;

    @Autowired
    PaperService paperService;


    @Override
    public void onMessage(MessageExt messageExt) {
        log.error("收到定时消息");
        PaperMessage paperMessage = JSON.parseObject(new String(messageExt.getBody()), PaperMessage.class);
        log.error("paperId-----"+Objects.toString(paperMessage.getPaperId()));
        Integer paperId = paperMessage.getPaperId();
        Integer userId = paperMessage.getUserId();
        //查询下该试卷是否还在数据库，不在的话就不提交了
        Paper paper = paperService.getBaseMapper().selectById(paperId);
        if(Objects.isNull(paper)){
            log.error("试卷已被删除，定时交卷取消");
            return;
        }
        //读取缓存中的试卷信息
        Object o = redisTemplate.opsForHash().get(RedisContant.QUESTION_RECORD_CACHE, userId.toString()+"_"+paperId.toString());
        if(o==null){
            log.error("缓存中没有试卷信息，用户"+userId+"定时提交试卷失败!");
            return ;
        }
        PaperWitnQuestionDto paperWitnQuestionDto = JSON.parseObject((String) o, PaperWitnQuestionDto.class);
        paperService.autoSubmitPaper(paperWitnQuestionDto);

        System.out.println("定时交卷任务完成");
    }
}

